const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
  cors: {
    origin: "*", // 允许所有来源
    methods: ["GET", "POST"],
    credentials: true
  }
});

// 存储在线用户和房间信息
const onlineUsers = new Map();
const rooms = new Map();
const userRooms = new Map(); // 跟踪用户已加入的房间

// 尝试不同端口的函数
async function startServer(initialPort) {
  const maxAttempts = 10;
  let currentPort = initialPort;

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      await new Promise((resolve, reject) => {
        const server = http.listen(currentPort, () => {
          console.log(`服务器成功运行在端口 ${currentPort}`);
          resolve();
        });

        server.on('error', (error) => {
          if (error.code === 'EADDRINUSE') {
            console.log(`端口 ${currentPort} 已被占用，尝试端口 ${currentPort + 1}`);
            currentPort++;
            server.close();
            reject(error);
          } else {
            reject(error);
          }
        });
      });
      return; // 如果成功启动，退出函数
    } catch (error) {
      if (attempt === maxAttempts - 1) {
        console.error('无法找到可用端口，请检查系统端口使用情况');
        process.exit(1);
      }
    }
  }
}

// 启用 CORS
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

io.on('connection', (socket) => {
  console.log('用户已连接:', socket.id);

  // 用户加入特定房间
  socket.on('join_room', (data) => {
    const { userData, room } = data;
    
    // 检查用户是否已经在房间中
    if (userRooms.get(socket.id)?.has(room)) {
      console.log(`用户 ${userData.name} 已经在房间 ${room} 中`);
      return;
    }

    // 将用户加入房间
    socket.join(room);
    onlineUsers.set(socket.id, { ...userData, room });
    
    // 更新用户房间记录
    if (!userRooms.has(socket.id)) {
      userRooms.set(socket.id, new Set());
    }
    userRooms.get(socket.id).add(room);
    
    // 获取房间内的用户列表
    const roomUsers = Array.from(onlineUsers.entries())
      .filter(([_, user]) => user.room === room)
      .map(([_, user]) => user);
    
    // 通知房间内所有用户
    io.to(room).emit('user_list', roomUsers);
    console.log(`用户 ${userData.name} 加入房间 ${room}`);
  });

  // 处理房间内的消息
  socket.on('room_message', (data) => {
    const { room, message } = data;
    const sender = onlineUsers.get(socket.id);
    
    if (sender && userRooms.get(socket.id)?.has(room)) {
      // 广播消息给房间内所有用户
      io.to(room).emit('new_message', {
        ...message,
        sender: sender.id,
        room: room
      });
      
      // 发送确认给发送者
      socket.emit('message_sent', {
        messageId: message.id,
        status: 'sent',
        room: room
      });
    }
  });

  // 处理消息已读状态
  socket.on('message_read', (data) => {
    const { room, messageIds } = data;
    const reader = onlineUsers.get(socket.id);
    
    if (reader) {
      // 通知房间内所有用户消息已读状态
      io.to(room).emit('message_status_update', {
        messageIds,
        status: 'read',
        reader: reader.id,
        room: room
      });
    }
  });

  // 用户离开房间
  socket.on('leave_room', (room) => {
    socket.leave(room);
    userRooms.get(socket.id)?.delete(room);
    
    const userData = onlineUsers.get(socket.id);
    if (userData) {
      onlineUsers.delete(socket.id);
      io.to(room).emit('user_list', 
        Array.from(onlineUsers.entries())
          .filter(([_, user]) => user.room === room)
          .map(([_, user]) => user)
      );
    }
  });

  // 用户断开连接
  socket.on('disconnect', () => {
    const userData = onlineUsers.get(socket.id);
    if (userData) {
      const rooms = userRooms.get(socket.id);
      if (rooms) {
        rooms.forEach(room => {
          socket.leave(room);
          io.to(room).emit('user_list', 
            Array.from(onlineUsers.entries())
              .filter(([_, user]) => user.room === room)
              .map(([_, user]) => user)
          );
        });
      }
      onlineUsers.delete(socket.id);
      userRooms.delete(socket.id);
      console.log(`用户 ${userData.name} 断开连接`);
    }
  });
});

// 添加健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok' });
});

// 启动服务器
const PORT = process.env.PORT || 3001;
startServer(PORT).catch(error => {
  console.error('服务器启动失败:', error);
  process.exit(1);
});